package com.azzcs.codeservicealibaba.service.impl;

import com.azzcs.codeservicecore.service.CodeService;
import com.azzcs.emailservicecore.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @Author: wzg
 * @Date: 2021/2/22 下午3:47
 */
@Slf4j
@Service
public class CodeServiceImpl implements CodeService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Reference
    private EmailService emailService;

    @Override
    public Integer createCode(String email) {
        String createCodeKey = getCreateCodeKey(email);
        String code = createCode();
        redisTemplate.opsForValue().set(createCodeKey,code,10, TimeUnit.MINUTES);
        emailService.sendCreateCodeEmail(email,code);
        return -1;
    }

    private String getCreateCodeKey(String email){
        return "create"+":"+email;
    }

    private String createCode(){
        Random random = new Random();
        Integer code = random.nextInt(999999);
        if(code - 100000 < 0){
            code = code+100000;
        }
        return String.valueOf(code);
    }

    @Override
    public Boolean checkCode(String email, Integer code) {
        String createCodeKey = getCreateCodeKey(email);
        Object o = redisTemplate.opsForValue().get(createCodeKey);
        if(o == null){
            return false;
        }
        redisTemplate.delete(createCodeKey);
        int redisCode = Integer.parseInt(String.valueOf(o));
        return code.equals(redisCode);
    }
}
